

using System.Diagnostics.CodeAnalysis;
using System.Linq;
using BootstrapBlazor.Components;
using Identity.Extensions;
using Identity.Interface;
using Identity.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Identity;


namespace   Identity.Account.Setting;

/// <summary>
/// 
/// </summary>
public partial class UserListManage: ComponentBase 
{
    [Inject]
    [NotNull]
    private DialogService? DialogService { get; set; }

    [Inject]
    [NotNull]
    private ToastService? ToastService { get; set; }


    private   Table<User>   UserTable = new Table<User>();

    [Inject]
    [NotNull]
    private IRole? RoleService { get; set; }

    [Inject]
    [NotNull]
    private IUser? UserService { get; set; }


     [Inject]
    [NotNull]
     private MyIdentityContext? AppContext { get; set; }




    [Inject]
    [NotNull]
    private UserManager<User>? UserManager { get; set; }
 
    // private static bool GetDisabled(string? id) => !string.IsNullOrEmpty(id);

    private List<IValidator> UserRules { get; } = new List<IValidator>();

    /// <summary>
    /// OnInitialized 方法
    /// </summary>
    protected override void OnInitialized()
    {

        base.OnInitialized();
    }
        [NotNull]
       private User  Users { get; set; } = new User();
private Task<QueryData<User>> OnQueryAsync(QueryPageOptions options)
  {
      var menus = UserService.GetAll();
     
 var ret = new QueryData<User>()
        {
            IsSorted = true,
            IsFiltered = true,
            IsSearch = true,
            IsAdvanceSearch=true,
        
        };

        var filter = options.ToFilter();
        if (options.IsPage)
        {
            var items = menus.AsQueryable()
                                .Where(filter.GetFilterLambda<User>(), filter.HasFilters())
                                .Sort(options.SortName!, options.SortOrder, !string.IsNullOrEmpty(options.SortName))
                                .Count(out var count)
                                .Page((options.PageIndex - 1) * options.PageItems, options.PageItems);

            ret.TotalCount = count;
            ret.Items = items;
        }
        else
        {
            var items = menus.AsQueryable()
                                .Where(filter.GetFilterLambda<User>(), filter.HasFilters())
                                .Sort(options.SortName!, options.SortOrder, !string.IsNullOrEmpty(options.SortName))
                                .Count(out var count);
            ret.TotalCount = count;
            ret.Items = items;
        }
        return Task.FromResult(ret);

     
  }
    private async Task OnAssignmentRoles(User user)
    {
        var groups = RoleService.GetAll().ToSelectedItemList();
        var values = RoleService.GetRolesByUserId(user.Id);

        await DialogService.ShowAssignmentDialog($"分配角色 - 当前用户: {user}", groups, values, () =>
        {
            var ret = RoleService.SaveRolesByUserId(user.Id, values);
            return Task.FromResult(ret);
        }, ToastService);
    }


        private async Task OnResetPassword(User user)
        {    
            var  user1=   await  UserManager.FindByIdAsync(user.Id);
            var token = await UserManager.GeneratePasswordResetTokenAsync(user1);
            var result = await UserManager.ResetPasswordAsync(user1, token, "123456");
            await ToastService.Show( new ToastOption(){ Title=result.Succeeded?"成功":"失败", Content = result.Succeeded ? "重置密码成功" : "重置密码失败", Category = result.Succeeded ? ToastCategory.Success : ToastCategory.Error });
        }


        private async Task OnLockUser(User user)
        {    
            var  user1=   await  UserManager.FindByIdAsync(user.Id);
            var result = await UserManager.SetLockoutEndDateAsync(user1, DateTimeOffset.MaxValue);
         await   UserTable.QueryAsync();
            await ToastService.Show( new ToastOption(){ Title=result.Succeeded?"成功":"失败", Content = result.Succeeded ? "锁定帐户成功" : "锁定帐户失败", Category = result.Succeeded ? ToastCategory.Success : ToastCategory.Error });
        }
        private  async Task<bool> OnSaveAsync(User model, ItemChangedType changedType)
        {    
             
            if (changedType == ItemChangedType.Add)
            {  
                model.Id=  Guid.NewGuid().ToString();
                model.ApprovedBy = AppContext.UserName;
                model.ApprovedTime = DateTime.Now;
                var result = await UserManager.CreateAsync(model, "123456");
                // await ToastService.Show( new ToastOption(){ Title=result.Succeeded?"成功":"失败", Content = result.Succeeded ? "添加账户成功" : "添加账户失败", Category = result.Succeeded ? ToastCategory.Success : ToastCategory.Error });
                return result.Succeeded;
            }   
            else
            {
                var user = await UserManager.FindByIdAsync(model.Id);
                
                user.Description = model.Description;
                user.DisplayName = model.DisplayName;
                user.PhoneNumber = model.PhoneNumber;
                user.Email = model.Email;
                user.WeChatId =model.WeChatId;
                user.NotificationType=model.NotificationType;
    
                var result = await UserManager.UpdateAsync(user);


                return result.Succeeded;
            }
         
        }


        private async Task  OnUnlockUser(User user)
        {    
            var  user1=   await  UserManager.FindByIdAsync(user.Id);
            var result = await UserManager.SetLockoutEndDateAsync(user1, null);
            await   UserTable.QueryAsync();
            await ToastService.Show( new ToastOption(){ Title=result.Succeeded?"成功":"失败", Content = result.Succeeded ? "解锁帐户成功" : "解锁帐户失败", Category = result.Succeeded ? ToastCategory.Success : ToastCategory.Error });
        }
   
}

